
// <copyright file="TransactSqlHelper.cs" company="Subhadra Software Solutions">
//   
// </copyright>
// <summary>
//   The transact sql helper.
// </summary>

namespace SubhadraSolutions.Sharp.Utils.Data.SqlServer
{
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;

    using Microsoft.SqlServer.TransactSql.ScriptDom;

    /// <summary>
    /// The transact sql helper.
    /// </summary>
    public static class TransactSqlHelper
    {
        #region Public Methods and Operators

        /// <summary>
        /// The remove comments from transact sql.
        /// </summary>
        /// <param name="sql">
        /// The sql.
        /// </param>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string RemoveCommentsFromTransactSql(string sql)
        {
            var parser = new TSql110Parser(true);
            IList<ParseError> errors;
            TSqlFragment fragments = parser.Parse(new StringReader(sql), out errors);

            // clear comments
            string result = string.Join(string.Empty, fragments.ScriptTokenStream.Where(x => x.TokenType != TSqlTokenType.MultilineComment).Where(x => x.TokenType != TSqlTokenType.SingleLineComment).Select(x => x.Text));

            return result;
        }

        #endregion Public Methods and Operators
    }
}